
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using NHibernate;
 // ERROR: Not supported in C#: OptionDeclaration
namespace NCS_CS
{
	internal class DBdata
	{
//将对数据库的操作汇集于此

		public string getsystemPwd()
		{
			try {
				string vname = null;
				vname = "system";
				string s = null;
				s = "select * from muser  where mname='" + vname + "'";
				IList rec = null;
				NCS.muser m = null;
				rec = ModMain.getsession().CreateSQLQuery(s).AddEntity(typeof(NCS.muser)).List();
				if (rec.Count == 1) {
                    m = (NCS.muser)rec[0];
					return m.mpassword;
				} else {
					return "";
				}
			} catch (System.Exception e) {
				modLog.savelogmsg(e.ToString() );
				return "";
			}
		}
        //public bool getdemo()
        //{
        //    try {
        //        ModMain.program1= (NCS.program)ModMain.getsession().Get(typeof(NCS.program), 1);
        //        return ModMain.program1.demo;
        //    } catch (System.Exception e) {
        //        modLog.savelogmsg(e.ToString()); 
        //        return false;
        //    }
        //}
        public  void getProgram1()
        {
            try
            {
                ModMain.program1 = (NCS.program)ModMain.getsession().Get(typeof(NCS.program), 1);
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }


		//Public Sub delVoltnewOne(ByVal vSid As Integer)
		//    Dim cmd As IDbCommand
		//    cmd = getsession().Connection.CreateCommand()
		//    cmd.CommandText = "delete * from voltnew where sampleid=" + CStr(vSid)
		//    cmd.ExecuteNonQuery()


		//End Sub
        //public void updateNewSampleid(int id, int newid, string sname)
        //{
        //    string s = null;
        //    IDbCommand cmd = null;
        //    cmd = ModMain.getsession().Connection.CreateCommand();
        //    s = "update sample set sampleid=" + Convert.ToString(newid) + ",cname='" + Convert.ToString(sname) + "' where id=" + Convert.ToString(id);
        //    cmd.CommandText = s;
        //    cmd.ExecuteNonQuery();
            
        //    ModMain.getsession().Flush();
        //}
        //public void insertAveOne(int vSid)
        //{
        //    string s = null;
        //    IDbCommand cmd = null;
        //    cmd = ModMain.getsession().Connection.CreateCommand();
        //    s = "INSERT INTO sampleAve SELECT avg(sample.c) AS c,stdev(sample.c) AS cstd, avg(sample.s) AS s,stdev(sample.s) AS sstd, max(sample.mdate) AS mdate, count(*) as num,sample.sampleid AS sampleid, max(sample.cname) AS cname, max(sample.cuser) AS cuser FROM sample WHERE sampleid=" + Convert.ToString(vSid) + " GROUP BY sampleid";
        //    cmd.CommandText = s;
        //    cmd.ExecuteNonQuery();
        //    //ModMain.getsession().Flush();
        //}
		public DBdata() : base()
		{
			//con = New ADODB.Connection
			//con.ConnectionString = constr
			//con.CursorLocation = ADODB.CursorLocationEnum.adUseClient
			//con.Open()
			//rec.ActiveConnection = con
			//rec2 = New RecordSet(constr)
			//cmd.ActiveConnection = con
		}


        //protected override void Finalize()
        //{
        //    base.Finalize();
        //}
		public bool loadUser(string vname)
		{
			try {
                ModMain.user1 = (NCS.muser)ModMain.getsession().Get(typeof(NCS.muser), vname);
				if (ModMain.user1 == null) {
					return false;
				} else {
					myLoadmethodByid(ModMain.user1.mname, ModMain.user1.methodid);

					return true;
				}
			} catch (System.Exception e) {
				modLog.savelogmsg(e.ToString()); 
				modLog.savelogmsg("end loadUser error");
				return false;
			}
		}
		public void myLoadmethodByid(string u, int methodid)
		{
			try {
				ModMain.method1 =(NCS.method ) ModMain.getsession().Get(typeof(NCS.method), methodid);
                checkChanel();
				return;
			} catch (System.Exception e) {
				modLog.savelogmsg(e.ToString()); 
			}
		}
        void checkChanel()
        {
            ArrayList l;
            ISession s = ModMain.getsession();
            NCS.curveXishu todelete=null;
            do
            {
                l=new ArrayList();
                todelete = null;
                foreach (NCS.curveXishu x in ModMain.method1.curveXishuList)
                {
                    if (x.ele == null || (x.ele != "C" && x.ele != "S" && x.ele != "C2" && x.ele != "S2"))//剔除无效
                    {
                        todelete = x;
                    }
                    else
                    {
                        if (l.Contains(x.ele))
                        {
                            todelete = x;
                        }
                        else
                        {
                            l.Add(x.ele);
                        }
                    }
                }
                if (todelete != null)
                {
                    ModMain.method1.curveXishuList.Remove(todelete);//剔除重复
                }
                else
                {
                    break;
                }
            } while (true);
            bool b = l.Contains("C");
            if (l.Count < 4)
            {
                ValidChanel(ref l, "C"); ValidChanel(ref l, "S"); ValidChanel(ref l, "C2"); ValidChanel(ref l, "S2");
            }
            s.Update(ModMain.method1);
            s.Flush();
        }
        void ValidChanel(ref ArrayList l, string ele)
        {
            if (l.Contains(ele))
            { }
            else
            {
                addChanel(ele);
            }
        }
        void addChanel(string ele)
        {
            NCS.curveXishu x = new NCS.curveXishu();
            x.ele = ele;
            ModMain.method1.curveXishuList.Add(x);

        }
		public void saveUser(ref NCS.muser user1)
		{

				ModMain.getsession().Update(user1);
				ModMain.getsession().Flush();
		}

        //public void saveUseHistory()
        //{
        //}
        //public void saveUseHistoryEndTime()
        //{
        //    //Dim s As String
        //    //s = "select * from usehistory where starttime=cvdate('" + CStr(user1.starttime) + "')"
        //    // ''debug.print s
        //    //If rec.State = 1 Then rec.Close()
        //    //Call rec.Open(s) ', con, adOpenDynamic, adLockOptimistic)
        //    //If rec.RecordCount > 0 Then
        //    //    rec.Fields("endtime").Value = Now
        //    //    rec.Update()
        //    //End If
        //    //    rec.Close
        //}

		public void addCurvexishu(int id)
		{
			NCS.method m = null;
			IList i = null;
			i = ModMain.getsession().CreateSQLQuery("select * from method where id=" + Convert.ToString(id)).AddEntity(typeof(NCS.method)).List();
			if (i.Count > 0) {
				m = (NCS.method )i[0];
				NCS.curveXishu xishu = new NCS.curveXishu();
				xishu.ele = "C";
				xishu.method = m;
				m.curveXishuList.Add(xishu);
				NCS.curveXishu xishu2 = new NCS.curveXishu();
				xishu2.ele = "S";
				xishu2.method = m;
				m.curveXishuList.Add(xishu2);
				NCS.curveXishu xishu3 = new NCS.curveXishu();
				xishu3.ele = "C2";
				xishu3.method = m;
				m.curveXishuList.Add(xishu3);
				NCS.curveXishu xishu4 = new NCS.curveXishu();
				xishu4.ele = "S2";
				xishu4.method = m;
				m.curveXishuList.Add(xishu4);
				ModMain.getsession().Save(m);
				ModMain.getsession().Flush();
			}
		}
        //public void newcopyCurveXishu(ref NCS.method m2, ref NCS.method method1)
        //{
        //    NCS.curveXishu xs = null;
        //    //l = method1.curveXishuList.MemberwiseClone()
        //    foreach (NCS.curveXishu xs_loopVariable in method1.curveXishuList) {
        //        xs = xs_loopVariable;
        //        NCS.curveXishu xs2 = new NCS.curveXishu();
        //        xs2.bjsp = xs.bjsp;
        //        xs2.blankarea = xs.blankarea;
        //        xs2.calcmode = xs.calcmode;
        //        xs2.cishu = xs.cishu;
        //        xs2.cmax = xs.cmax;
        //        xs2.cmin = xs.cmin;
        //        xs2.x0 = xs.x0;
        //        xs2.x1 = xs.x1;
        //        xs2.ele = xs.ele;
        //        xs2.LINExishu = xs.LINExishu;
        //        xs2.must00 = xs.must00;
        //        newcopycurvedata(ref xs2, ref xs);
        //        xs2.method = m2;
        //        m2.curveXishuList.Add(xs2);
        //    }
        //}
        //public void newcopycurvedata(ref NCS.curveXishu m2, ref NCS.curveXishu method1)
        //{
        //    //NCS.curveData xs = null;
        //    //l = method1.curveXishuList.MemberwiseClone()
        //    foreach (NCS.curveData xs in method1.curveDataList) {
        //        //xs = xs_loopVariable;
        //        NCS.curveData xs2 = new NCS.curveData();
        //        xs2.calcconc = xs.calcconc;
        //        xs2.ele = xs.ele;
        //        xs2.eleArea = xs.eleArea;
        //        xs2.eleInt = xs.eleInt;
        //        xs2.quan = xs.quan;
        //        xs2.sampleid = xs.sampleid;
        //        xs2.standardid = xs.standardid;
        //        xs2.weight = xs.weight;
        //        xs2.wlweight = xs.wlweight;
        //        xs2.curveXishu = m2;
        //        m2.curveDataList.Add(xs2);
        //    }
        //}
        //public void copyMethod(int id, ref int nid, string newMethodName)
        //{
        //    try
        //    {
        //        NCS.method m2 = new NCS.method();
        //        m2.cname = newMethodName;
        //        m2.cuser = ModMain.method1.cuser;
        //        m2.cswitch = ModMain.method1.cswitch;
        //        m2.sswitch = ModMain.method1.sswitch;
        //        m2.flushtime = ModMain.method1.flushtime;
        //        m2.sampletime = ModMain.method1.sampletime;
        //        m2.smoothnum = ModMain.method1.smoothnum;
        //        m2.tuoqiTime = ModMain.method1.tuoqiTime;
        //        m2.wlC = ModMain.method1.wlC;
        //        m2.wlS = ModMain.method1.wlS;
        //        m2.jieqi = ModMain.method1.jieqi;
        //        newcopyCurveXishu(ref m2, ref ModMain.method1);
        //        ModMain.getsession().Save(m2);
        //        ModMain.getsession().Flush();
        //        ModMain.method1 = m2;

        //        nid = m2.ID;
        //        //copyCurveXishu(id, nid)
        //        //copyCurveData(id, nid)
        //        //method1 = getsession().Get(GetType(NCS.method), nid) 'reload
        //        return;
        //    }
        //    catch (System.Exception e)
        //    {
        //        modLog.savelogmsg(e.ToString());
        //        modLog.showLog();
        //    }
        //}
		public void execute(string s)
		{
			IDbCommand cmd = ModMain.getsession().Connection.CreateCommand();
			cmd.CommandText = s;
			cmd.ExecuteNonQuery();
		}
        //public void copyCurveXishu(int id, int nid)
        //{
        //    string s = null;
        //    //drop table tmp
        //    this.delTmpTable();
        //    s = "select methodid,ele,x0,x1,cmin,cmax   into tmp from curveXishu where methodid=" + Convert.ToString(id);
        //    execute(s);

        //    s = "update  tmp set methodid=" + Convert.ToString(nid);
        //    execute(s);

        //    s = "insert into curveXishu select * from tmp";
        //    execute( s);
        //}
		public void delTmpTable()
		{
			try {
				string s = null;
				//drop table tmp
				s = "drop table tmp";

				execute( s);
			} catch (System.Exception e) {
                modLog.savelogmsg(e.ToString()); 
			}
		}
        //public void copyCurveData(ref int id, ref int nid)
        //{
        //    string s = null;
        //    //drop table tmp
        //    this.delTmpTable();
        //    s = "select methodid,standardid,sampleid,ele,elearea,weight,quan  into tmp from curvedata where methodid=" + Convert.ToString(id);

        //    execute(s);
        //    s = "update  tmp set methodid=" + Convert.ToString(nid);

        //    execute(s);
        //    s = "insert into curvedata select * from tmp";

        //    execute(s);
        //}
		//Sub deleteMethod(ByRef methodname As String)
		//End Sub
        //public void deleteMethodByid(int id)
        //{
        //    NCS.method m = null;
        //    m = (NCS.method )ModMain.getsession().Get(typeof(NCS.method), id);
        //    ModMain.getsession().Delete(m);
        //    ModMain.getsession().Flush();

        //}

        //public string getLastUser()
        //{
        //    try {
        //        NCS.program P = null;
        //        P = (NCS.program )ModMain.getsession().Get(typeof(NCS.program), 1);
        //        return P.lastUser;
        //    } catch (System.Exception e) {
        //        modLog.savelogmsg("get lastuser error:");
        //        modLog.savelogmsg(e.ToString()); 
        //        return "";
        //    }
        //}
        //public void setLastUser( string mname)
        //{
        //    ModMain.program1.lastUser = mname;
        //}
        //public bool getAutoLogon()
        //{
        //    try {
        //        NCS.program P = null;
        //        P =(NCS.program ) ModMain.getsession().Get(typeof(NCS.program), 1);
        //        return P.autoLogon;
        //    } catch (System.Exception e) {
        //        modLog.savelogmsg("get autologon error:");
        //        modLog.savelogmsg(e.ToString()); 
        //        return false;
        //    }
        //}
        //public void setAutoLogon(ref bool auto_Renamed)
        //{
        //    try {
        //        string s = null;
        //        if (auto_Renamed) {
        //            s = "update  program set autologon=1 where id=1";
        //        } else {
        //            s = "update  program set autologon=0 where id=1";
        //        }
        //        execute(s);
        //        return;
        //    } catch (System.Exception e) {
        //        modLog.savelogmsg("set autologon error:");
        //        modLog.savelogmsg(e.ToString()); 
        //    }
        //}
        //public void changePwd(NCS.muser user1, string newpwd)
        //{
        //    try
        //    {
        //        user1.mpassword = newpwd;
        //        ModMain.getsession().Update(user1);
        //        ModMain.getsession().Flush();
        //    }
        //    catch (System.Exception e)
        //    {
        //        modLog.savelogmsg(e.ToString());
        //    }
        //}
        //public void setAnaXuhao(int sid)
        //{
        //    try {
        //        //Dim d As Date
        //        string s = null;
        //        s = "select * from sample  where sampleid=" + Convert.ToString(sid);
        //        s = s + " order by mdate";
        //        IList sl = null;
        //        sl = ModMain.getsession().CreateSQLQuery(s).AddEntity(typeof(NCS.sample)).List();
        //        //NCS.sample sm = null;
        //        int c = 0;

        //        foreach (NCS.sample sm in sl) {
        //            //sm = sm_loopVariable;
        //            {
        //                c = c + 1;
        //                sm.anaxuhao = (int)c;
        //            }
        //            ModMain.getsession().Update(sm);
        //            ModMain.getsession().Flush();
        //        }
        //    } catch (System.Exception e) {
        //        modLog.savelogmsg(e.ToString()); 
        //    }
        //}
		public void myLoadEleChanel()
		{
			try {
				ModMain.gchanel = ModMain.getsession().CreateCriteria(typeof(NCS.chanel)).List();
				ModMain.gchanelDic = new System.Collections.Generic.Dictionary<string, NCS.chanel >();
				foreach (NCS.chanel c in ModMain.gchanel) {
					ModMain.gchanelDic.Add(c.ele, c);
				}
			} catch (System.Exception e) {
				modLog.savelogmsg(e.ToString()); 
			}
		}

		public void getvlvset(ref int[] vlV, ref string[] vlvName, ref int nvlv)
		{
			getnumvlv(ref nvlv);
			vlvName = new string[nvlv];
			vlV = new int[nvlv];
			this.getVlvNameId(ref vlV, ref vlvName);
		}
		public void getDiSet(ref int[] vlV, ref string[] vlvName, ref int nvlv)
		{
			System.Collections.IList l = null;
			l = ModMain.getsession().CreateSQLQuery("select * from dichanel").AddEntity(typeof(NCS.diChanel)).List();
			nvlv =(int) l.Count;
			vlvName = new string[nvlv + 1];
			vlV = new int[nvlv + 1];
            //NCS.diChanel c = null;

			foreach (NCS.diChanel c in l) {
                //c = c_loopVariable;
				vlvName[c.id] = c.cname;
				vlV[c.id] = c.chanel;
			}
		}

		public void getnumvlv(ref int nvlv)
		{
			try {
				object o = null;
				o = ModMain.getsession().CreateQuery("select max(dc.id) from doChanel dc").UniqueResult();
				if ((o != null)) {
                    nvlv = (int)(Convert.ToInt16(o) + 1);
				} else {
					nvlv = 0;
				}
			} catch (System.Exception e) {
				modLog.savelogmsg(e.ToString()); 
			}
		}
		public void getVlvNameId(ref int[] vlV, ref string[] vlvName)
		{
			try {
				IList l = null;
				l = ModMain.getsession().CreateSQLQuery("select * from dochanel").AddEntity(typeof(NCS.doChanel)).List();
                //NCS.doChanel c = null;
				foreach (NCS.doChanel c in l) {
                    //c = c_loopVariable;
					vlV[c.id] = c.chanel;
					vlvName[c.id] = c.cname;
				}
				return;
			} catch (System.Exception e) {
				modLog.savelogmsg(e.ToString()); 
			}
		}

        //public int getTpModel()
        //{
        //    int functionReturnValue = 0;
        //    try {
        //        //Dim n As Integer
        //        NCS.program P = null;
        //        P = (NCS.program )ModMain.getsession().Get(typeof(NCS.program), 1);
        //        return P.tpid ;
        //    } catch (System.Exception e) {
        //        modLog.savelogmsg(e.ToString()); 
        //    }
        //    return functionReturnValue;
        //}
		public double getStandardConc(int id, string ele)
		{
			NCS.standard s = null;
			s = (NCS.standard )ModMain.getsession().Get(typeof(NCS.standard), id);
			if (s == null) {
				return 0;
			} else {
				if (ele == "C" | ele == "C2") {
					return s.cconc;
				} else {
					return s.sconc;
				}

			}
		}
        //public void insCurveData(int vMethodid, string vEle, int vStandardid, double vW, double vA, int Vsid, double vWlweight)
        //{
        //    //"insert into  curvedata(methodid,ele,standardid,weight,elearea,sampleid,wlWeight)  values(vMethodid,vEle,vStandardid,vW,vA,Vsid,vWlweight)"
        //    NCS.curveData d = null;
        //    d = new NCS.curveData();
        //    d.methodid = vMethodid;
        //    d.ele = vEle;
        //    d.standardid = vStandardid;
        //    d.weight = vW;
        //    d.eleArea = vA;
        //    d.sampleid = Vsid;
        //    d.wlweight = vWlweight;
        //    d.quan = 1;
        //    d.eleInt = getStandardConc(vStandardid, vEle);
        //    ModMain.getsession().Save(d);
        //    ModMain.getsession().Flush();
        //}
        public void delsig(int id)
        {
            IDbCommand cmd = null;
            cmd = ModMain.getsession().Connection.CreateCommand();
            cmd.CommandText = "delete * from voltnew where sampleid=" + Convert.ToString(id);
            cmd.ExecuteNonQuery();
        }
        //public void delaveOne(int id)
        //{
        //    IDbCommand cmd = null;
        //    cmd = ModMain.getsession().Connection.CreateCommand();
        //    cmd.CommandText = "delete * from sampleAve where sampleid=" + Convert.ToString(id);
        //    cmd.ExecuteNonQuery();
        //    //ModMain.getsession().Flush();
        //}
        public void insertIds(ArrayList ids)
        {
            IDbCommand cmd = null;
            ISession s = ModMain.getsession();
            cmd = s.Connection.CreateCommand();
            int sid;
                IEnumerator e = ids.GetEnumerator();
                while (e.MoveNext())
                {
                    try
                    {
                        sid = (int)e.Current;
                        cmd.CommandText = "insert into tmpid(sampleid) values(" + Convert.ToString(sid) + ")";
                        cmd.ExecuteNonQuery();
                    }
                    catch (System.Data.OleDb.OleDbException e1)
                    {
                        modLog.savelogmsg(e1.ToString());
                    }
                }
            s.Flush();

        }
		public void insertIdsOne(int sid)
		{
            try
            {
                IDbCommand cmd = null;
                cmd = ModMain.getsession().Connection.CreateCommand();
                cmd.CommandText = "insert into tmpid(sampleid) values(" + Convert.ToString(sid) + ")";
                cmd.ExecuteNonQuery();
                //ModMain.getsession().Flush();
            }
            catch (System.Data.OleDb.OleDbException e1)
            {
                ;
            }

		}
		public void delIDS()
		{
			//con.Execute("DELETE FROM tmpid")
			IDbCommand cmd = null;
			cmd = ModMain.getsession().Connection.CreateCommand();
			cmd.CommandText = "DELETE FROM tmpid";
			cmd.ExecuteNonQuery();
		}
		public void delidsOne(int ID)
		{
			//con.Execute("delete * from tmpid where sampleid=" + CStr(ID))
			IDbCommand cmd = null;
			cmd = ModMain.getsession().Connection.CreateCommand();
			cmd.CommandText = "delete * from tmpid where sampleid=" + Convert.ToString(ID);
			cmd.ExecuteNonQuery();
		}
		//As Object
        //public void saveTpModel( int id)
        //{
        //    //        try
        //    //        Dim s As String
        //    //        s = "update program set tpid=" + CStr(id)
        //    //        cmd.CommandText = s
        //    //        cmd.Execute()
        //    //        Exit Sub
        //    //Catch e As System.Exception

        //    //        saveerrmsg()
        //    //        Select Case Err.Number
        //    //            Case -2147467259 ' 操作必须使用一个可更新的查询。
        //    //                MsgBox("错误描述：" + Err.Description + vbCrLf + "提示:请检查data.mdb文件的只读属性！", MsgBoxStyle.Exclamation, "错误！")
        //    //        End Select
        //}
		public int getMethodId( string username, string methodname)
		{
			int id = 0;
			NCS.method m = null;
			IList i = null;
            i = ModMain.getsession().CreateSQLQuery("select * from method where cname='" + methodname + "' and cuser='" + username + "'").AddEntity(typeof(NCS.method)).List();
			if (i.Count > 0) {
				m = (NCS.method )i[0];
				id = m.ID;
			} else {
				id = 0;
			}
			return id;
		}
        //public int addNewMethod( string username,  string methodname,  int smooth, ref bool b)
        //{
        //    int methodid = 0;
        //    try {
        //        NCS.method m = new NCS.method();
        //        m.cname = methodname;
        //        m.cuser = username;
        //        m.cswitch = 9.9F;
        //        m.sswitch = 9.9F;
        //        m.sampletime = 15;
        //        m.flushtime = 10;
        //        m.tuoqiTime = 20;
        //        m.jieqi = true;
        //        ModMain.getsession().Save(m);
        //        ModMain.getsession().Flush();

        //        methodid = getMethodId( username,  methodname);
        //        b = true;
        //    } catch (System.Exception e) {
        //        modLog.savelogmsg(e.ToString()); 
        //        b = false;
        //    }
        //    return methodid;
        //}

		public bool getId00(ref int id)
		{
			try {
				string s = null;
				s = "select * from standard where cconc=0 and sconc=0";
				NCS.standard st = null;
				IList l = null;
				l = ModMain.getsession().CreateSQLQuery(s).AddEntity(typeof(NCS.standard)).List();

				if (l.Count > 0) {
					st = (NCS.standard )l[0];
					id = st.ID;
					return true;
				} else {
					return false;
				}
			} catch (System.Exception e) {
				modLog.savelogmsg(e.ToString()); 
				return false;
			}
		}
		public void addstandard00()
		{
			try {
				string s = null;
				s = "insert into standard(cconc,sconc) values(0,0)";
				execute( s);
				return;
			} catch (System.Exception e) {
				modLog.savelogmsg(e.ToString()); 
			}
		}

	}
}
